package com.linkage.cart.service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.linkage.user.pojo.User;

/**
 * .
 *
 * @author sunhao(sunhao.java@gmail.com)
 * @version V1.0, 2014-11-27 16:16
 */
@Service
public class LoginService4 {
    @Autowired
    private UserService4 userService;

    public boolean login(HttpServletRequest request, String loginName, String password) {
        if (StringUtils.isEmpty(loginName)) {
            return false;
        }

        User user = this.userService.loadByLoginName(loginName);

        if (user != null && password.equals(user.getPassword())) {
            storeInSession(request.getSession(), "LOGIN_USER_KEY_IN_SESSION", user);
            return true;
        }

        return false;
    }

    public boolean logout(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute("LOGIN_USER_KEY_IN_SESSION");
        if (obj == null || !(obj instanceof User))
            return false;

        request.getSession().removeAttribute("LOGIN_USER_KEY_IN_SESSION");
        return true;
    }

    private void storeInSession(HttpSession session, String key, Object object) {
        session.setAttribute(key, object);
    }
}
